package cn.cloud9;

import redis.clients.jedis.Jedis;

public class Service {

    private Integer aliveSec;
    private String userId;
    private Long limitUse;

    public Service(Integer aliveSec, String userId, Long limitUse) {
        this.aliveSec = aliveSec;
        this.userId = userId;
        this.limitUse = limitUse;
    }

    public void service() {
        Jedis jedis = new Jedis("192.168.2.225", 6379);
        try {
            String compId = "compId:" + this.userId;
            String idVal = jedis.get(compId);
            if (null == idVal) {
                String resp = jedis.setex(compId, this.aliveSec, String.valueOf(Long.MAX_VALUE - this.limitUse));
            } else {
                Long incr = jedis.incr(compId);
                incr = this.limitUse - (Long.MAX_VALUE - incr);
                business(incr);
            }
        } catch (Exception exception) { // exception.getMessage()
            System.out.printf("用户：%s 操作达到上限!\n", this.userId);
        } finally {
            jedis.close();
        }
    }

    public void business(Long count) {
        System.out.printf("用户：%s 执行业务逻辑部分的代码... 次数：%s\n", this.userId, count);
    }


}
